﻿using MaterialManagement.API.Application.Command.ERP;
using MaterialManagement.Domain.ERP;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Interface;
using MediatR;

namespace MaterialManagement.API.Application.Handler.ERP
{
    public class GetOutboundRecordHandler : IRequestHandler<GetOutboundRecordCommand, APIResult<List<OutboundRecordModel>>>
    {
        private readonly IBaseRepository<OutboundRecordModel> outboundRecordRepo;
        private readonly IBaseRepository<PickingModel> pickingRepo;

        public GetOutboundRecordHandler(IBaseRepository<OutboundRecordModel> outboundRecordRepo,
                                        IBaseRepository<PickingModel> pickingRepo)
        {
            this.outboundRecordRepo = outboundRecordRepo;
            this.pickingRepo = pickingRepo;
        }
        public Task<APIResult<List<OutboundRecordModel>>> Handle(GetOutboundRecordCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<OutboundRecordModel>> result = new APIResult<List<OutboundRecordModel>>();
            var res = outboundRecordRepo.GetAll().Where(x => !x.IsDel && x.PickState == true);
            var query = res.ToList();
            foreach (var order in query)
            {
                order.PickInfo = pickingRepo.GetAll().Where(x => x.PickFormCode == order.PickFormCode).Count();
                order.PickTotal = pickingRepo.GetAll().Where(x => x.PickFormCode == order.PickFormCode).Select(x=>x.PickingQuantity).Sum();
            }
            result.Data = query;
            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            return Task.FromResult(result);
        }
    }
}
